package com.cjm.task3.service;

import com.cjm.task3.dao.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class GetDataService {
    @Scheduled(cron = "${JiangMing.Schedules.updateData}")
    public List<RegionStats> getData() throws IOException {
        List<RegionStats> data = new ArrayList<>();
        String uriTemplate = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        //爬取全球新型冠状病毒统计数据的csv文件
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(uriTemplate))
                //如果直接使用HTTP客户端请求Gitee上的文件，会报403的错误，但使用浏览器访问是正常的
                //我们使用HTTP客户端请求Gitee上的文件时，需要设置一个请求头部User-Agent(如下面的KHTML)，否则会报403异常
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"))
                .build();
        ResponseEntity<Resource> response = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = response.getBody();

        //通过Resource对象的getInputStream方法获取csv文件的输入流
        InputStream inputStream = body.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);

        Reader in = new BufferedReader(reader);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
        for (CSVRecord record : records) {
            RegionStats data1 = new RegionStats();
            data1.setState(record.get("Province/State"));
            data1.setCountry(record.get("Country/Region"));
            data1.setLatestTotalCases(Integer.parseInt((record.get(record.size()-1))));
            data1.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
            data.add(data1);
        }
        return data;
    }

}
